<template>
    <div class="fan-app-container">
      <div class="fan-container">
        <div class="fan-assembly">
          <div class="fan-head">
            <div class="fan-blades-assembly" :style="bladeContainerStyle">
              <svg class="fan-blades" viewBox="0 0 100 100" preserveAspectRatio="xMidYMid meet">
                <path d="M50 50 L45 12 Q50 2 55 12 Z" fill="#B9E2F5" />
                <path d="M50 50 L45 12 Q50 2 55 12 Z" fill="#B9E2F5" transform="rotate(90 50 50)" />
                <path d="M50 50 L45 12 Q50 2 55 12 Z" fill="#B9E2F5" transform="rotate(180 50 50)" />
                <path d="M50 50 L45 12 Q50 2 55 12 Z" fill="#B9E2F5" transform="rotate(270 50 50)" />
                <circle cx="50" cy="50" r="10" fill="#79BCDD" />
                <circle cx="50" cy="50" r="7" fill="#52A8D1" />
              </svg>
            </div>
            <div class="fan-grill">
              <div v-for="i in 12" :key="`grill-${i}`" class="grill-line" :style="{ transform: `rotate(${i * 15}deg)` }"></div>
            </div>
          </div>
          <div class="fan-neck"></div>
          <div class="fan-pole"></div>
          <div class="fan-base"></div>
        </div>
  
        <div class="controls">
          <button type="button" @click="togglePower" :class="{ active: isOn }" class="control-button power-button">
{{ isOn ? '关闭' : '开启' }}
          </button>
          <button type="button" @click="setSpeed(1)" :disabled="!isOn" :class="{ active: isOn.value && currentSpeed.value === 1 }" class="control-button speed-button">
            一档
          </button>
          <button type="button" @click="setSpeed(2)" :disabled="!isOn" :class="{ active: isOn && currentSpeed.value === 2 }" class="control-button speed-button">
            二档
          </button>
          <button type="button" @click="setSpeed(3)" :disabled="!isOn" :class="{ active: isOn.value && currentSpeed.value === 3 }" class="control-button speed-button">
            三档
          </button>
        </div>
        <div class="status-display">
          状态: <span :class="{ 'status-on': isOn, 'status-off': !isOn }">{{ isOn ? '运行中' : '已关闭' }}</span>
          <span v-if="isOn"> | 档位: {{ currentSpeed }}</span>

        </div>
      </div>
    </div>
  </template>
  
  <script setup>
  import { ref, computed, onUnmounted } from 'vue';
  
  // 风扇运行的状态和速度
  const isOn = ref(false); // 是否开启
  const currentSpeed = ref(0); // 当前运行速度（0表示关闭，1-3表示速度）
  const selectedSpeed = ref(1); // 用户选择的速度（1-3），默认为1
  const rotationAngle = ref(0); // 当前旋转角度
  let animationFrameId = null; // 用于存储requestAnimationFrame的ID
  
  
  // 设置不同速度对应的转速
  // 0: 关闭
  // 1: 1.5
  // 2: 3.5
  // 3: 7
  const speedSettings = {
    0: 0,  // Off
    1: 1.5, // Slowest speed
    2: 3.5, // Medium speed
    3: 7,   // Fastest speed
  };
  
  // Computed style for the blade assembly to apply rotation
  const bladeContainerStyle = computed(() => {
    return {
      transform: `rotate(${rotationAngle.value}deg)`,
    };
  });
  
  // Animation loop for rotating the blades
  function animateBlades() {
    if (isOn.value && currentSpeed.value > 0) {
      rotationAngle.value = (rotationAngle.value + speedSettings[currentSpeed.value]) % 360;
      animationFrameId = requestAnimationFrame(animateBlades);
    } else {
      // If fan is off or speed is 0, cancel animation frame
      if (animationFrameId) {
        cancelAnimationFrame(animationFrameId);
        animationFrameId = null;
      }
    }
  }
  
  // Toggles the fan's power state
  function togglePower() {
    if (!isOn.value) { // If fan is currently OFF, we are turning it ON
      currentSpeed.value = selectedSpeed.value; // Set the current speed to the last selected speed
      isOn.value = true;                         // Update the power state to ON
      // console.log('Turning ON. Status should update. isOn:', isOn.value, 'currentSpeed:', currentSpeed.value);
      animateBlades(); // Start animation
    } else { // If fan is currently ON, we are turning it OFF
      // 启动减速过程：每200ms减少1档，直到速度为0
      const slowDownInterval = setInterval(() => {
        if (currentSpeed.value > 0) {
          currentSpeed.value -= 1;
        } else {
          clearInterval(slowDownInterval);
          isOn.value = false;                        // 最终更新为关闭状态
          if (animationFrameId) {
            cancelAnimationFrame(animationFrameId);
            animationFrameId = null;
          }
        }
      }, 300);
      // 保持isOn为true直到减速完成
      // console.log('开始减速. currentSpeed:', currentSpeed.value);
    }
  }
  
  // Sets the fan speed - only effective if fan is OFF, as buttons are disabled when ON
  function setSpeed(speed) {
    selectedSpeed.value = speed; // 更新选择的档位
    currentSpeed.value = speed; // 直接更新当前档位（无论是否开启）
    
    if (!isOn.value) {
      isOn.value = true; // 若关闭状态点击，同时开启风扇
      animateBlades(); // 启动动画
    } else {
      // 若已开启，直接更新动画速度
      animateBlades(); // 重新触发动画确保速度变化生效
    }
    // If fan was somehow ON and this function was callable (e.g. programmatically),
    // then we might update currentSpeed if it's already on.
    // else {
    //   currentSpeed.value = speed;
    //   if (!animationFrameId && speed > 0) {
    //     animateBlades();
    //   } else if (speed === 0 && animationFrameId) {
    //       cancelAnimationFrame(animationFrameId);
    //       animationFrameId = null;
    //   }
    // }
  }
  
  // Cleanup animation frame on component unmount
  onUnmounted(() => {
    if (animationFrameId) {
      cancelAnimationFrame(animationFrameId);
    }
  });
  </script>
  
  <style scoped>
  .fan-app-container {
    display: flex;
    justify-content: center;
    align-items: flex-start;
    min-height: 100vh;
    padding: 20px;
    background-color: #e0f7fa; /* Lighter cyan background for overall page */
    box-sizing: border-box;
  }
  
  .fan-container {
    display: flex;
    flex-direction: column;
    align-items: center;
    font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
    padding: 25px;
    background-color: #ffffff;
    border-radius: 15px;
    box-shadow: 0 10px 25px rgba(0, 0, 0, 0.1), 0 6px 10px rgba(0,0,0,0.05);
    width: 320px;
  }
  
  .fan-assembly {
    display: flex;
    flex-direction: column;
    align-items: center;
    margin-bottom: 25px;
  }
  
  .fan-head {
    width: 200px;
    height: 200px;
    background-color: #A0D2EB; /* Light Blue for head */
    border-radius: 50%;
    position: relative;
    display: flex;
    margin-bottom: -20px; /* Slight overlap with pole */;
    justify-content: center;
    align-items: center;
    border: 6px solid #79BCDD; /* Darker Light Blue border */
    box-shadow: inset 0 0 15px rgba(0,0,0,0.1), 0 2px 5px rgba(0,0,0,0.05);
  }
  
  .fan-grill {
      position: absolute;
      width: 100%;
      height: 100%;
      pointer-events: none;
  }
  
  .grill-line {
      position: absolute;
      top: 50%;
      left: 0;
      width: 100%;
      height: 1.5px;
      background-color: rgba(121, 188, 221, 0.6); /* Semi-transparent darker blue for grill */
      transform-origin: center;
  }
  .fan-grill::before, .fan-grill::after {
      content: '';
      position: absolute;
      left: 50%;
      top: 50%;
      transform: translate(-50%, -50%);
      border-radius: 50%;
      border: 1.5px solid rgba(121, 188, 221, 0.6); /* Semi-transparent darker blue for grill */
  }
  .fan-grill::before {
      width: 70%;
      height: 70%;
  }
  .fan-grill::after {
      width: 40%;
      height: 40%;
  }
  
  
  .fan-blades-assembly {
    width: 170px;
    height: 170px;
    position: relative;
    z-index: 5;
  }
  
  .fan-blades {
    width: 100%;
    height: 100%;
  }
  
  .fan-neck {
    width: 30px;
    height: 25px;
    /* Gradient adjusted for light blue theme */
    background: linear-gradient(to bottom, #A0D2EB, #79BCDD);
    margin-top: -10px; /* Ensures connection with head */
    position: relative;
    z-index: -1;
    border-radius: 5px 5px 0 0;
  }
  
  .fan-pole {
    width: 25px;
    height: 180px;
    /* Gradient adjusted for light blue theme */
    background: linear-gradient(to bottom, #A0D2EB, #79BCDD);
    box-shadow: 0 2px 4px rgba(0,0,0,0.1);
  }
  
  .fan-base {
    width: 120px;
    height: 35px;
    background-color: #79BCDD; /* Darker Light Blue for base */
    border-radius: 20px 20px 8px 8px;
    margin-top: -5px; /* Slight overlap with pole bottom */
    box-shadow: 0 4px 8px rgba(0,0,0,0.2);
    position: relative;
  }
  .fan-base::before {
      content: '';
      position: absolute;
      top: 5px;
      left: 5px;
      right: 5px;
      bottom: 5px;
      border-radius: 15px 15px 3px 3px;
      box-shadow: inset 0 2px 5px rgba(0,0,0,0.15);
  }
  
  
  .controls {
    margin-top: 10px;
    display: grid;
    grid-template-columns: repeat(2, 1fr);
    gap: 12px;
    width: 100%;
    max-width: 280px;
  }
  
  .control-button {
    padding: 12px 10px;
    border: none;
    border-radius: 8px;
    color: white;
    cursor: pointer;
    font-size: 15px;
    font-weight: 500;
    transition: background-color 0.25s ease, transform 0.1s ease, box-shadow 0.25s ease;
    box-shadow: 0 2px 5px rgba(0,0,0,0.1);
  }
  .control-button:hover:not(:disabled) {
    transform: translateY(-1px);
    box-shadow: 0 4px 8px rgba(0,0,0,0.15);
  }
  .control-button:active:not(:disabled) {
    transform: translateY(0px);
    box-shadow: inset 0 2px 4px rgba(0,0,0,0.1);
  }
  
  
  .power-button {
    background-color: #ef5350; /* Slightly softer red */
  }
  .power-button.active {
    background-color: #66bb6a; /* Slightly softer green */
  }
  .power-button:hover:not(.active) {
    background-color: #e53935;
  }
  .power-button.active:hover {
    background-color: #43a047;
  }
  
  
  .speed-button {
    background-color: #42a5f5; /* Softer blue for speed buttons */
  }
  .speed-button:hover:not(:disabled) {
    background-color: #1e88e5;
  }
  .speed-button.active { /* This style will apply to background even if disabled */
    background-color: #1565c0; /* Darker blue for active speed indicator */
    box-shadow: inset 0 2px 4px rgba(0,0,0,0.2);
  }
  .speed-button:disabled {
    background-color: #bdbdbd; /* Standard grey for disabled */
    color: #757575;
    cursor: not-allowed;
    box-shadow: none;
  }
  
  .status-display {
    margin-top: 20px;
    font-size: 15px;
    color: #37474f; /* Darker blue-grey text */
    padding: 8px 12px;
    background-color: #eceff1; /* Light grey-blue background */
    border-radius: 6px;
    text-align: center;
    min-width: 180px;
  }
  .status-on {
    color: #43a047; /* Softer Green */
    font-weight: bold;
  }
  .status-off {
    color: #e53935; /* Softer Red */
    font-weight: bold;
  }
  
  </style>
  